package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-27
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckInDetailVo selectCheckInById(Long id)
    {
        //1.查询入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //2.查询老人信息
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectElderById(elderId);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        LocalDate birth = LocalDate.parse(elder.getBirthday(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        int age = Period.between(birth, LocalDate.now()).getYears();
        checkInElderVo.setAge(age);
        //3.查询合同信息
        Contract contract = contractMapper.selectContractByElderId(elder.getId());
        //4.查询入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectCheckInConfigByCheckInId(id);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        LocalDateTime startDate = contract.getStartDate();
        LocalDateTime endDate = contract.getEndDate();
        checkInConfigVo.setStartDate(startDate);
        checkInConfigVo.setEndDate(endDate);
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        //5.查询老人亲属信息(数据库中checkin的remark备注里)
        String relations = checkIn.getRemark();
        //5.1转换亲属列表：把数据库中存储的json格式的集合数据转变成正常的集合数据
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(relations, ElderFamilyVo.class);
        //6.整合数据返回
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);

        return checkInDetailVo;
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     * @param checkInApplyDto
     * @return
     */
    @Override
    public void applyCheckIn(CheckInApplyDto checkInApplyDto) {
        //1.判断老人是否已经入住
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        String idCardNo = checkInElderDto.getIdCardNo();
        Elder e1 =  elderMapper.selectElderByIdCardNo("1",idCardNo);

        if(e1 != null){
            throw new BaseException("该老人已入住");
        }
        //2.更新床位状态为已入住
        Bed bed = new Bed();
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        Long bedId = checkInConfigDto.getBedId();
        bed.setId(bedId);
        bed.setRoomId(checkInConfigDto.getRoomId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3.新增或更新老人信息
        Elder elder = insertOrUpdate(checkInApplyDto.getCheckInElderDto(), bedId, checkInElderDto.getIdCardNo());

        //4.新增合同信息
        insertContract(checkInApplyDto,elder);

        //6.新增入住信息
        CheckIn checkIn = insertCheckIn(elder, checkInApplyDto);

        //5.新增入住配置信息
        insertCheckInConfig(checkInApplyDto, checkIn);



    }

    /**
     * 新增或更新入住老人信息
     * @param checkInElderDto
     * @param bedId
     * @param idCardNo
     * @return
     */
    @Override
    public Elder insertOrUpdate(CheckInElderDto checkInElderDto,  Long bedId , String idCardNo) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto,elder);
        elder.setCreateTime(DateUtils.getNowDate());
        elder.setStatus(1);
        elder.setBedId(bedId);
        Bed bed1 = bedMapper.selectBedById(bedId);
        elder.setBedNumber(bed1.getBedNumber());
        //判断老人未入住但数据库中是否存在数据

        Elder e2 = elderMapper.selectElderByIdCardNo("0", idCardNo);
        if(e2 != null){
            elderMapper.updateElder(elder);
        }else{
            elderMapper.insertElder(elder);
        }
        return elder;
    }

    /**
     * 新增合同
     * @param checkInApplyDto
     * @param elder
     */
    @Override
    public void insertContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = new Contract();
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        BeanUtils.copyProperties(checkInContractDto,contract);
        contract.setCreateTime(DateUtils.getNowDate());
        contract.setElderId(elder.getId());
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(1);

        contractMapper.insert(contract);
    }

    /**
     * 新增入住信息
     * @param elder
     * @param checkInApplyDto
     * @return
     */
    @Override
    public CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
        checkInMapper.insertCheckIn(checkIn);
        return checkIn;
    }

    /**
     * 新增入住配置信息
     * @param checkInApplyDto
     * @param checkIn
     */
    @Override
    public void insertCheckInConfig(CheckInApplyDto checkInApplyDto, CheckIn checkIn) {
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insertCheckInConfig(checkInConfig);
    }


}
